#include "GY_PopupMenu.h"
#include "ui_GY_PopupMenu.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QDebug>
#include <QFile>
#include <QDir>

GY_PopupMenu::GY_PopupMenu(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::GY_PopupMenu)
{
    ui->setupUi(this);

    ui->treeWidget->setHeaderLabel("");

    //没有菜单数据文件则创建
    QFile loadFile("OperatorMenu.json");

    if(!loadFile.exists()){
        if(loadFile.open((QIODevice::WriteOnly))){
            QJsonArray root;
            QJsonObject group;
            group["group"] = "Flow";
            QJsonArray item;
            QJsonObject itemObj;

            itemObj["name"] = "Start";
            itemObj["type"] = "StartEnd";
            itemObj["PI"] = QJsonArray();
            QJsonArray po;
            po.append("default");
            itemObj["PO"] = po;
            itemObj["DI"] = QJsonArray();
            itemObj["DO"] = QJsonArray();
            itemObj["tips"] = "开始";
            item.append(itemObj);

            itemObj["name"] = "End";
            itemObj["type"] = "StartEnd";
            QJsonArray pi;
            pi.append("default");
            itemObj["PI"] = pi;
            itemObj["PO"] = QJsonArray();
            itemObj["DI"] = QJsonArray();
            itemObj["DO"] = QJsonArray();
            itemObj["tips"] = "结束";
            item.append(itemObj);

            itemObj["name"] = "Branch";
            itemObj["type"] = "Branch";
            itemObj["PI"] = pi;
            {
                QJsonArray po;
                po.append("True");
                po.append("False");
                itemObj["PO"] = po;
            }
            QJsonArray di;
            di.append("Condition");
            itemObj["DI"] = di;
            itemObj["DO"] = QJsonArray();
            itemObj["tips"] = "分支";
            item.append(itemObj);

            group["item"] = item;
            root.append(group);

            QJsonObject groupFunc;
            groupFunc["group"] = "Function";
            groupFunc["item"] = QJsonArray();
            root.append(groupFunc);

            QJsonDocument doc;
            doc.setArray(root);
            QByteArray fileData = doc.toJson(QJsonDocument::Compact);
            QString jsonStr(fileData);
            QTextStream in(&loadFile);
            in.setCodec("UTF-8");  //处理中文问题
            in << jsonStr;
            loadFile.close();
        }
    }

    //
    QTreeWidgetItem* functionItem = nullptr;
    if(loadFile.open(QIODevice::ReadWrite)){
        QString strModelJson;
        QTextStream jsonStream(&loadFile);
        jsonStream.setCodec("UTF-8");  //处理中文解析失败问题
        while(!jsonStream.atEnd()){
            strModelJson.append(jsonStream.readLine());
        }
        loadFile.close();
        QJsonParseError e;
        QJsonDocument doc;
        doc = QJsonDocument::fromJson(strModelJson.toUtf8(),&e);
        if(e.error == QJsonParseError::NoError){
            //qDebug()<<doc.isObject();  //
            QJsonObject obj = doc.object();
            QJsonArray array = obj["root"].toArray();
            bool flowLoad = false; //流程选项已加载
            for(QJsonValue val : array){
                QTreeWidgetItem* parent = new QTreeWidgetItem(ui->treeWidget,QStringList(val.toObject()["group"].toString()));
                ui->treeWidget->addTopLevelItem(parent);
                if(flowLoad){
                    functionItem = parent;  //第二个group为Python函数
                    break;  //只在此文件读取流程选项并加载
                }
                for(QJsonValue v: val.toObject()["item"].toArray()){
                    QJsonDocument d;
                    d.setObject(v.toObject());
                    parent->addChild(new QTreeWidgetItem(parent,{v.toObject()["name"].toString(),QString(d.toJson(QJsonDocument::Compact))}));

                }
                flowLoad = true;
            }
        }
    }

    //读取python文件夹所有py文件生成功能菜单
    QFileInfoList list = FindAllFiles("./python", "py");
//    qDebug()<<list;

    for(QFileInfo fileInfo : list){
        QFile file(fileInfo.filePath());
        if(file.open(QIODevice::ReadOnly)){

            QString fileName = fileInfo.fileName();
            QString package = fileName.left(fileName.indexOf("."));



            QString strFile;
            QTextStream textStream(&file);
            textStream.setCodec("UTF-8");  //处理中文解析失败问题
            while(!textStream.atEnd()){
                QString line = textStream.readLine();
                strFile.append(line);
//                //直接import其py文件即可
//                if(line.contains("import ")){
//                    imports.append(line);
//                }

                QString suffix = "def ";
//                if(line.contains(suffix)){  //嵌套函数
                if(0 == line.indexOf(suffix)){
                    //构建Function，默认有返回值
                    //json格式："{'name':'Function','PI':['default'],'PO':['default'],'DI':[],'DO':['ret']}"
                    QString funcDefLine = line.right(line.length() - line.indexOf(suffix) - suffix.length() ).trimmed();  //去掉suffix
                    QString funcName = funcDefLine.left(funcDefLine.indexOf("(")).trimmed();
                    funcName = package + "." + funcName;
                    funcDefLine = funcDefLine.right(funcDefLine.length() - funcDefLine.indexOf("(") -1).trimmed();
                    funcDefLine = funcDefLine.left(funcDefLine.indexOf(")")).trimmed();
                    QStringList funcParamList;
                    if(!funcDefLine.isEmpty()){
                        funcParamList = funcDefLine.split(",");
                    }
                    QString strParams;
                    bool firstParam = true;
                    for(QString param : funcParamList){
                        param = param.trimmed();
                        if(!firstParam){
                            strParams.append(",");
                        }
                        strParams.append("\"" + param + "\"");
                        firstParam = false;
                    }


                    //默认一个返回值
                    QString json = QString("{\"name\":\"%1\",\"PI\":[\"default\"],\"PO\":[\"default\"],\"DI\":[%2],\"DO\":[\"ret\"]}")
                                    .arg(funcName).arg(strParams);
                    functionItem->addChild(new QTreeWidgetItem(functionItem,{funcName,json}));
                }
            }
            file.close();

        }

    }
}

GY_PopupMenu::~GY_PopupMenu()
{
    delete ui;
}

QFileInfoList GY_PopupMenu::FindAllFiles(const QString &strDir, const QString &suffix)
{
    QFileInfoList retList;

    QDir dir(strDir);
    if(!dir.exists()){
        return retList;
    }
//    QStringList filter;
//    filter.append("*.py");
//    dir.setNameFilters(filter);
    dir.setFilter(QDir::Dirs | QDir::Files);
    dir.setSorting(QDir::DirsFirst);
    QFileInfoList list = dir.entryInfoList(/*filter*/);

    int i = 0;
    bool isDir = false;
    do{
        QFileInfo fileInfo = list.at(i);
        if(fileInfo.fileName() == "." || fileInfo.fileName() == ".."){
            i++;
            continue;
        }

        isDir = fileInfo.isDir();
        if(isDir){
            retList.append(FindAllFiles(fileInfo.filePath(), suffix));
        }
        else{
            if("*" == suffix || fileInfo.suffix() == suffix){
                retList.append(fileInfo);
            }
        }

        i++;
    }
    while(i < list.size());

    return retList;
}

void GY_PopupMenu::on_treeWidget_itemDoubleClicked(QTreeWidgetItem *item, int column)
{
    if(item->parent()&& item->columnCount() > 1){
        hide();

        emit InsertItem(item->text(1).replace("'","\""));



    }
}

void GY_PopupMenu::on_lineEdit_textChanged(const QString &arg1)
{
//    QList<QTreeWidgetItem*> items = ui->treeWidget->findItems(arg1.trimmed(),Qt::MatchContains|Qt::MatchRecursive);

    QTreeWidgetItemIterator itor(ui->treeWidget);
//    if(!arg1.trimmed().isEmpty()){
        while (*itor) {

            (*itor)->setHidden( !(*itor)->text(0).contains(arg1.trimmed(),Qt::CaseInsensitive));
            ++itor;
        }
//    }else{
//        while (*itor) {
//            (*itor)->setHidden(false);
//            ++itor;
//        }
//    }
}

QStringList GY_PopupMenu::getPackages()
{
    //读取python文件夹所有py文件
    QStringList packages;
    QFileInfoList list = GY_PopupMenu::FindAllFiles("./python", "py");
//    qDebug()<<list;

    for(QFileInfo fileInfo : list){
        QFile file(fileInfo.filePath());
        if(file.open(QIODevice::ReadOnly)){
            QString fileName = fileInfo.fileName();
            QString package = fileName.left(fileName.indexOf("."));
            packages.append(package);
            file.close();
        }
    }
    return packages;
}

const QString GY_PopupMenu::findItemJsonStr(const QString itemName)
{
    QString jsonStr;
    QTreeWidgetItemIterator itor(ui->treeWidget);
    while (*itor) {
        if(itemName == (*itor)->text(0) ){
            jsonStr = (*itor)->text(1);
            break;
        }
        ++itor;
    }
    return jsonStr;
}
